package
{
	import com.bit101.components.InputText;
	import com.bit101.components.PushButton;
	import com.bit101.components.TextArea;
	
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	
	[SWF(height="480", width="320")]
	public class HddnchtFlash extends TopLevel
	{
		private var _input : InputText;
		private var _button :  PushButton;
		private var _textArea : TextArea;
		private var _padding : int = 5;
		
		private var _socket : Socket;
		
		public function HddnchtFlash()
		{
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			_button = new PushButton(null, 0, 0, "Send", buttonClick);
			_input = new InputText();
			_input.height = _button.height;
			_textArea = new TextArea();
			_textArea.autoHideScrollBar = true;
			TopLevel.stage.addChild(_input);
			TopLevel.stage.addChild(_button);
			TopLevel.stage.addChild(_textArea);
			
			TopLevel.stage.addEventListener(Event.RESIZE, paint);
			paint();
			
			_socket = new Socket("10.4.6.233", 4444);
			_socket.addEventListener(Event.CONNECT, onConnect);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
			_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, security);
		}
		
		private function paint(event:Event = null):void
		{
			_button.x = TopLevel.stage.stageWidth - _button.width - _padding;
			_button.y = TopLevel.stage.stageHeight - _button.height - _padding;
			
			_input.x = _padding;
			_input.y = TopLevel.stage.stageHeight - _input.height - _padding;
			_input.width = _button.x - 2 * _padding;
			
			_textArea.width = TopLevel.stage.stageWidth - 2 * _padding;
			_textArea.x = _padding;
			_textArea.y = _padding;
			_textArea.height = _button.y - 2 * _padding;
			
			
		}
		
		private function buttonClick(event : MouseEvent):void
		{
			trace("CLICK");
			try
			{
				_socket.writeUTFBytes(_input.text);
				_socket.flush();
			} 
			catch(error:Error) 
			{
				trace("handle");
			}
			
			_input.text = "";
		}
		
		protected function onConnect(event:Event):void
		{
			_socket.writeUTFBytes("MY CHICK GOOD");
			_socket.flush();
			_textArea.text += "Enter your name";
			trace("connected");
			_socket.addEventListener(ProgressEvent.SOCKET_DATA, dataRecieved);
		}
		
		protected function dataRecieved(event:ProgressEvent):void
		{
			trace("data recieved");
			var inMsg:String = _socket.readUTFBytes(_socket.bytesAvailable);
			trace(inMsg);
			_textArea.text += inMsg + "\n";
			//_socket.flush();
		}
		
		protected function onError(event:Event):void
		{
			trace("got error!");
		}
		
		protected function security(event:Event):void
		{
			trace("security error");
		}
		
		
	}
	
}